﻿
using CRM.Infrastructure.Attr;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace Crm.Infrastructure.IOC
{
    public static class Inject_Helper
    {

        /// <summary>
        /// 自定义批量注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="providers"></param>
        /// <param name="injects"></param>
        public static void AddScope(this IServiceCollection services, Assembly providers, Assembly injects)
        {
            var pros = providers.GetTypes()
                .Where(d => d.GetCustomAttribute(typeof(Provider_Attribute)) != null).ToList();
            var injs = injects.GetTypes().Where(d => d.GetCustomAttribute(typeof(Inject_Attribute)) != null).ToList();
            pros.ForEach(d =>
            {
                var ins = injs.Where(e => d.IsAssignableFrom(e)).FirstOrDefault();
                if (ins != null)
                {
                    services.AddScoped(d, ins);
                }
            });
        }

        /// <summary>
        /// 自定义批量注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="providers"></param>
        /// <param name="injects"></param>
        public static void AddTransient(this IServiceCollection services, Assembly providers, Assembly injects)
        {
            var pros = providers.GetTypes()
                .Where(d => d.GetCustomAttribute(typeof(Provider_Attribute)) != null).ToList();
            var injs = injects.GetTypes().Where(d => d.GetCustomAttribute(typeof(Inject_Attribute)) != null).ToList();
            pros.ForEach(d =>
            {
                var ins = injs.Where(e => d.IsAssignableFrom(e)).FirstOrDefault();
                if (ins != null)
                {
                    services.AddScoped(d, ins);
                }
            });
        }

        /// <summary>
        /// 自定义批量注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="providers"></param>
        /// <param name="injects"></param>
        public static void AddSingleton(this IServiceCollection services, Assembly providers, Assembly injects)
        {
            var pros = providers.GetTypes()
                .Where(d => d.GetCustomAttribute(typeof(Provider_Attribute)) != null).ToList();
            var injs = injects.GetTypes().Where(d => d.GetCustomAttribute(typeof(Inject_Attribute)) != null).ToList();
            pros.ForEach(d =>
            {
                var ins = injs.Where(e => d.IsAssignableFrom(e)).FirstOrDefault();
                if (ins != null)
                {
                    services.AddScoped(d, ins);
                }
            });
        }


    }
}
